$(function(){
    initBidModelEvent();
    initSubmitEvent();
    VIPRule();
    ServantRule();
    backTrade();
    //初始化上传plupload控件
    createPlupload('browse','goods',uploadedImageCallback);
});

/**
 * 表单校验集成
 */
function initSubmitEvent(){
    $('#submitForm').validate({
        debug: true, //调试模式取消submit的默认提交功能
        focusInvalid: false,
        onkeyup: false,
        submitHandler: function(form){
            if (typeof jQuery.data(this, "disabledOnSubmit") == 'undefined') {
                var warnMessage = checkAndReturnWarnMessage(form);
                var submit = true;
                if(warnMessage && !confirm(warnMessage)) {
                    submit = false;
                }
                var  imageCount =$("#imageList div.imageflag");
                if (imageCount.length>5){
                    alert("最多只能上传5张图片");
                    submit = false;
                }
                var backTradeDelayDays1 = $("#backTradeDelayDays1").val();
                if (backTradeDelayDays1=="-1"){
                    $("#backTradeDelayDays").val("-1");
                }
                if(submit){
                    jQuery.data(this, "disabledOnSubmit", {submited : true});
                    save(this);
                }
            } else {
            }
        },
        success:function(element){
            element.siblings("span[class='error red']").text("");
        },
        errorPlacement : function(error, element) {
            if(error.text()){
                if(element.next("span[class='error red']").size() == 0){
                    element.after("<span class='error red'>" + error.text() +"</span>");
                }else{
                    element.next("span[class='error red']").text(error.text());
                }
            }else{
                element.next("span[class='error red']").remove();
            }
        },

        rules:{
            templateName:{required:true},
            beginPrice:{isIntDigit:10},
            reservePrice:{isIntDigit:10},
            priceIncrease:{isFloatGtZero:true,isIntDigit:10},
            promiseMoney:{isIntDigit2:12},
            endPrice:{
                isIntDigit2:12,
                isFloatGteThen:["#reservePrice"],
                customRule:(function(){
                    var endPrice = $("#endPrice").val();
                    var beginPrice = $("#beginPrice").val();
                    var priceIncrease = $("#priceIncrease").val();
                    if (endPrice) {
                        var m =  Math.pow(10,1);
                        return (parseFloat(endPrice) > parseFloat(beginPrice)) && ((Math.round(((parseFloat(endPrice))*100) * m) / m) - (Math.round(((parseFloat(beginPrice))*100) * m) / m)) % (Math.round(((parseFloat(priceIncrease))*100) * m) / m) == 0;
                    }else{
                        return true;
                    }
                })
            },
            maxBidLimit:{
                conditionRequired:checkBidMaxLimitRequired
            },
            fixRewardMoney:{isIntDigit:10},
            fixCommissionMoney:{isIntDigit:10},
            fixBuyerFee:{isIntDigit:10},
            fixSellChangeMoney:{isIntDigit:10},
            storageFee:{isIntDigit:10,min:0},
            relativePrice:{isIntDigit:10,min:0},
            costPrice:{isIntDigit:10,min:0},
            admittanceMoney:{isIntDigit:10,min:0}
        },
        messages:{
            goodsCode:{remote:"该编号已存在"},
            priceIncrease:{isFloatGtZero:"请输入大于0的数字"},
            endPrice: {
                isFloatGteThen: "请输入大于或等于保留价的值",
                customRule: "请输入有效的出价价格(加价幅度的倍数+底价)"
            }
        }
    });
}

/**
 * 返回表单中maxBixLimit字段的必填判断
 * @returns {Boolean}
 */
function checkBidMaxLimitRequired(){
    return $("#modelCheckBox").val() == 'freeQuoteBid' && $("select[name='maxBidLimitOption']").val() == '1';
}

/**
 * 注册竞购模式的选择事件
 * 注册次数限制的下拉框选择事件
 */
function initBidModelEvent(){
    var defaultModel = $("#modelCheckBox").val();
    selectBidModelPane(defaultModel?defaultModel:'fixBid');
    $("input[name=bidModel]").bind("click",function(){
        console.log($(this).val());
        selectBidModelPane($(this).val());
    });

    selectMaxBidLimitPane($("select[name='maxBidLimitOption']").val());
    $("select[name='maxBidLimitOption']").bind("change",function(){
        selectMaxBidLimitPane($(this).val());
    });
}

/**
 * 根据竞购模式不同，展示不同的form内容
 * @param model
 */
function selectBidModelPane(model){
    $(".dynamic").hide();
    $(".dynamic." + model).show();
    //TODO:因模式整改为可配置的展示,每次变更都需要隐藏域来设置
    $("#modelCheckBox").val(model);

    changeForm(model);
    //清空非本模式下的表单域数据
    $(".dynamic").not("." + model).find("input").val("");
    //清理交易信息DIV下的错误提示DOM
    $("form").find("div.tradeInfo").find("td span[class='error red']").remove();
}

function selectMaxBidLimitPane(val){
    if(val == "1"){
        $("input[name='maxBidLimit']").show();
    }else{
        $("input[name='maxBidLimit']").hide();
        $("input[name='maxBidLimit']").val("");
    }
}

/**
 * 校验保证金是否满足奖励金额
 * 校验卖家手续费是否满足奖励金额
 * @param form
 * @returns
 */
function checkAndReturnWarnMessage(form){
    var warnMessage;
    var formData = $(form).serializeJSON();
    var bidModel = formData.bidModel;
    if(bidModel == "freeQuoteBid" || bidModel == "reducePriceBid"){
        //检查保证金是否涵盖(出价奖励+返佣+买方手续费)
        var promiseMoney 			= formData.promiseMoney?parseFloat(formData.promiseMoney):0;
        var fixRewardMoney 			= formData.fixRewardMoney?parseFloat(formData.fixRewardMoney):0;
        var fixCommissionMoney 		= formData.fixCommissionMoney?parseFloat(formData.fixCommissionMoney):0;
        var fixBuyerFee 			= formData.fixBuyerFee?parseFloat(formData.fixBuyerFee):0;
        var fixSellerFee 			= formData.fixSellChangeMoney?parseFloat(formData.fixSellChangeMoney):0;
        var storageFee				= formData.storageFee?parseFloat(formData.storageFee):0;
        var bidRewardRate = formData.bidRewardRadio?parseFloat(formData.bidRewardRadio):0;
        var equalRewardRate = formData.equalRewardRadio?parseFloat(formData.equalRewardRadio):0;
        var beginPrice = formData.beginPrice?parseFloat(formData.beginPrice):0;
        //var fixSellerFee 			= (actulSellerFee + fixRewardMoney + fixCommissionMoney + storageFee).toFixed(2);
        //填充固定卖方手续费
        //$("#fixSellChangeMoney").val(fixSellerFee);
        var tipsMessageFormArray = [];
        if (bidModel == "freeQuoteBid") {
            tipsMessageFormArray.push("固定出价奖励:" + fixRewardMoney);
            tipsMessageFormArray.push("固定返佣奖励:" + fixCommissionMoney);
        }else {
            if (beginPrice == 0){
                tipsMessageFormArray.push("最底价设置为0,,最终成交价可能为0");
            }
            tipsMessageFormArray.push("出价奖励比例:" + bidRewardRate+"%");
            tipsMessageFormArray.push("返佣奖励比例:" + equalRewardRate+"%");
        }
        tipsMessageFormArray.push("固定保证金金额:" + promiseMoney);
        tipsMessageFormArray.push("固定买方手续费:" + fixBuyerFee);

        warnMessage = tipsMessageFormArray.join('\n') + '\n\n 请确认信息后提交?';
    }else{
        var promiseRate = formData.promiseRadio?parseFloat(formData.promiseRadio):0;
        var bidRewardRate = formData.bidRewardRadio?parseFloat(formData.bidRewardRadio):0;
        var equalRewardRate = formData.equalRewardRadio?parseFloat(formData.equalRewardRadio):0;
        var buyerFeeRate = formData.buyChangeMoney?parseFloat(formData.buyChangeMoney):0;
        var sellerFeeRate = formData.sellChangeConey?parseFloat(formData.sellChangeConey):0;
        //var sellerFeeRate = (actulSellerFeeRate + bidRewardRate + equalRewardRate).toFixed(2);
        //填充卖方手续费比例
        //$("#sellChangeConey").val(sellerFeeRate);
        var tipsMessageFormArray = [];
        tipsMessageFormArray.push("出价奖励比例:" + bidRewardRate+"%");
        tipsMessageFormArray.push("返佣奖励比例:" + equalRewardRate+"%");
        tipsMessageFormArray.push("保证金比例:" + promiseRate+"%");
        tipsMessageFormArray.push("买方手续费比例:" + buyerFeeRate+"%");

        warnMessage = tipsMessageFormArray.join('\n') + '\n\n 请确认信息后提交?';
    }
    return warnMessage;
}

function openCommissionRateWindow(id) {
    window.open(appServer+'/goods/getUser.htm?id='+id, 'newwindow', 'height=400, width=1000, top=20,left=150, toolbar=no, menubar=no, scrollbars=yes, resizable=no,location=no, status=no').focus();
}

function changeClassifyId(classifyId) {
    if(classifyId != '') {
        jQuery.ajax({
            type:"post",
            url:appServer + "/goods/ajax/getClassify.htm",
            dataType:"json",
            data:{"classifyId":classifyId},
            success:function(message){
                var classifyList = message.classifyList;
                $('#classifyIdCheck').empty();
                $('#classifyIdCheck').prepend("<option value=''>请选择</option>");
                if(classifyList != null) {
                    for(var i=0;i<classifyList.length;i++ ) {
                        var classify = classifyList[i];
                        $('#classifyIdCheck').append("<option value='" + classify.id + "'>" +classify.name  + "</option>");
                    }
                }
            },
            error:function(xhr, message, e){

            }
        });
    }
}

function num(obj){
    obj.value = obj.value.replace(/[^\d.]/g,""); //清除"数字"和"."以外的字符
    obj.value = obj.value.replace(/^\./g,""); //验证第一个字符是数字
    obj.value = obj.value.replace(/\.{2,}/g,"."); //只保留第一个, 清除多余的
    obj.value = obj.value.replace(".","$#$").replace(/\./g,"").replace("$#$",".");
    obj.value = obj.value.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3'); //只能输入两个小数
    if(parseFloat(obj.value)>100){
        obj.value = 100;
    }
}
function checkvalue(obj){
    obj.value = obj.value.replace(/[^\d.]/g,""); //清除"数字"和"."以外的字符
    obj.value = obj.value.replace(/^\./g,""); //验证第一个字符是数字
    obj.value = obj.value.replace(/\.{2,}/g,"."); //只保留第一个, 清除多余的
    obj.value = obj.value.replace(".","$#$").replace(/\./g,"").replace("$#$",".");
    obj.value = obj.value.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3'); //只能输入两个小数
}

function changeForm(model){
    $("#changeTitle,#endPriceChangeTitle").empty();
    if(model=="freeQuoteBid" || model=="reducePriceBid"){
        $("#changeTitle").append("<span style='color:red'>*</span>固定保证金(元)：");
        if (model=="reducePriceBid") {
            $("#endPriceChangeTitle").append("<span style='color:red'>*</span>起始价(元)：");
        }else {
            $("#endPriceChangeTitle").append("<span style='color:red'>*</span>最高价(元)：");
        }
    }else{
        $("#changeTitle").append("<span style='color:red'>*</span>初始保证金(元)：");
        $("#endPriceChangeTitle").append("封顶价(元)：");
    }
    if (model=="reducePriceBid") {
        $("#beginPriceChangeTitle").empty();
        $("#beginPriceChangeTitle").append("<span style='color:red'>*</span>最低价(元)：");
        $("#changePriceIncreaseTitle").empty();
        $("#changePriceIncreaseTitle").append("<span style='color:red'>*</span>降价幅度(元)：");
    }else {
        $("#beginPriceChangeTitle").empty();
        $("#beginPriceChangeTitle").append("<span style='color:red'>*</span>起始价(元)：");
        $("#changePriceIncreaseTitle").empty();
        $("#changePriceIncreaseTitle").append("<span style='color:red'>*</span>加价幅度(元)：");
    }
}

function changeFixBuyerFee(promiseMoney){
    if(promiseMoney == 0){
        var bidModel = $("#modelCheckBox").val();
        if( bidModel == "fixBid" || bidModel == "freeBid"){
            return;
        }else{
            $("#fixBuyerFee").val(0);
            $("input[name='fixBuyerFee']").attr("readonly","readonly")
        }
    }else{
        $("input[name='fixBuyerFee']").removeAttr("readonly");
    }
}

/**
 * 图片上传回显
 * @param data
 */
function uploadedImageCallback(data){
    if(data.status == 200 ){
        data = $.parseJSON(data.response);
        var imagePath = imageServer +'/' + data.result[0].smallImageUrl;
        var	innerHtml = '<div class="imageflag" title="双击图片进行删除" ondblclick="deleteCurrentImage(this);" style="display: inline-block" >';
        innerHtml += '<input type="hidden" id="imageType" name="imageList[][imageType]" value="0" />';
        innerHtml += '<img src="' + imagePath + '" width="100px;" height="100px;"/>';
        innerHtml += '<input type="radio" id="imageRadio" name="imageRadio" style="background-image: url('+ imagePath +')" value="0" onclick="changeImageType(this);"/>';
        innerHtml += '<input type="hidden" name="imageList[][bigImageUrl]" value="' + data.result[0].bigImageUrl+ '"/>';
        innerHtml += '<input type="hidden" name="imageList[][smallImageUrl]" value="' + data.result[0].smallImageUrl+ '"/>';
        innerHtml += '<input type="hidden" name="imageList[][originalImageUrl]" value="' + data.result[0].originalImageUrl+ '"/>';
        innerHtml += '</div>';
        //图片赋值
        $(innerHtml).prependTo('#imageList');
    }
}
/**
 * 删除/移除图片DOM元素
 */
function deleteCurrentImage(obj) {
    $(obj).remove();
}
/**
 * 选中首页轮播图
 */
function changeImageType(obj) {
    var inps = document.getElementsByTagName('input');
    for(var i = 0,inp; inp = inps[i++];){
        if(inp.id == 'imageType'){
            inp.value = '0';
        }
    }
    var images = '0';
    $('#imageType').val(images);
    var image = '1';
    $(obj).parent('div').find('#imageType').val(image);
    alert("选中的图片为商品logo");
}

function save(obj){
    var requestJson = $("form").serializeJSON();
    $.ajax({
        url: appServer + "/goods/template/add.json",
        type: "POST",
        contentType : 'application/json;charset=utf-8', //设置请求头信息
        dataType:"json",
        data: JSON.stringify(requestJson),
        success: function(data){
            if(data.code == 0){
                alert(data.msg);
                window.location.href = appServer + "/goods/template/list.htm";
            }else{
                alert(data.msg);
                inite(obj);
            }
        },
        error: function(res){
            alert(res.responseText);
            inite(obj);
        }
    });
}

function inite(obj) {
    jQuery.removeData(obj,"disabledOnSubmit");
}

function selectRooms() {
    window.open(appServer+'/goods/platformRoom/getRooms.htm?callBack=setRooms', 'newwindow', 'height=400, width=1000, top=20,left=150, toolbar=no, menubar=no, scrollbars=yes, resizable=no,location=no, status=no').focus();
}

function setRooms(json){
    $("input[name='platformRooms[id]']").val(json.roomId);
    $("input[name='platformRooms[roomName]']").val(json.roomName);
}

function clearRooms(){
    $("input[name='platformRooms[id]']").val("");
    $("input[name='platformRooms[roomName]']").val("");
}

function VIPRule() {
    var rewardMode = $("#rewardMode").val();
    if (rewardMode == 'Y') {
        var bidRewardMode = $("#bidRewardMode").val();
        if (bidRewardMode == "VIP") {
            getRuleRate();
            //caculateChangeRate();
        }
        bidRewardMode = $("#bidRewardMode").val();
        $(".bidRewardMode").hide();
        $(".bidRewardMode." + bidRewardMode).show();
    }else {
        $("#bidRewardMode").val("COMMON");
    }
}
function ServantRule() {
    var rewardServantMode = $("#rewardServantMode").val();
    if (rewardServantMode == 'Y') {
        var bidServantMode = $("#bidServantMode").val();
        if (bidServantMode == "PLATE") {
            var plateId = $("#plateIdCheck").val();
            if (plateId == "") {
                alert("请先选中专场");
                $("#bidServantMode").val("COMMON");
                return;
            } else {
                plate(plateId);
                //caculateChangeRate();
            }
        }

        bidServantMode = $("#bidServantMode").val();
        $(".bidServantMode").hide();
        $(".bidServantMode." + bidServantMode).show();
    }else {
        $("#bidServantMode").val("COMMON");
    }
}
function getRuleRate() {
    jQuery.ajax({
        async: false,
        type:"post",
        url:appServer + "/transaction/levelReward/getRuleRate.json",
        dataType:"json",
        success: function(result){
            if (result.code != 0){
                alert(result.message);
                $("#bidRewardMode").val("COMMON");
                $("#bidRewardRadio").val("");
            }else {
                var data = $.parseJSON(result.data);
                $("#bidRewardRateSpan").text("[最高比例" + data.rewardRate + "%,"+ data.name +"]");
                $("#bidRewardRate").val(data.rewardRate);
                $("#bidRewardRadio").val(data.rewardRate);
            }
        },
        error: function(){
        }
    });
}

function plate(plateId) {
    jQuery.ajax({
        async: false,
        type:"post",
        url:appServer + "/transaction/commissionReward/checkPlate.json",
        dataType:"json",
        data:{"plateId":plateId},
        success: function(result){
            if(result.code == 0){
                var data = $.parseJSON(result.data);
                var tipsMessageArray = [];
                var maxBidServantRate = 0;
                if(data.PLATFORM){
                    if (parseFloat(data.PLATFORM.bidServantRate) > maxBidServantRate) {
                        maxBidServantRate = parseFloat(data.PLATFORM.bidServantRate);
                    }
                    tipsMessageArray.push("平台:" + data.PLATFORM.bidServantRate + "%");
                }
                if (data.USER) {
                    if (parseFloat(data.USER.bidServantRate) > maxBidServantRate) {
                        maxBidServantRate = parseFloat(data.USER.bidServantRate);
                    }
                    tipsMessageArray.push("回拍:" + data.USER.bidServantRate + "%");
                }
                //取最大值
                $("#bidServantRate").val(maxBidServantRate);
                $("#equalRewardRadio").val(maxBidServantRate);
                if (tipsMessageArray.length > 0) {
                    $("#bidServantModeSpan").text("[" + tipsMessageArray.join(",") + "]");
                }
            } else {
                alert("该专场未绑定规则，请重选专场或选择自定义");
                $("#bidServantMode").val("COMMON");
            }
        },
        error: function(){
        }
    });
}

//是否回拍选择
function backTrade() {
    var selectedValue = $("#backTradeDelayDays1").val();
    if(selectedValue == "-1"){
        $("#backTradeDelayDays").val('');
        $(".backTradeDelayDaysSpan").hide();
    } else {
        $(".backTradeDelayDaysSpan").show();
    }
}

/**
 * 所属专场选项变更事件
 * @param obj
 */
function changePlateOption(obj){
	//返佣策略检查及设置
	ServantRule();
	//商品折扣比例检查及设置
	obtainDiscountRates(obj);
}

/**
 * 获取专场信息，填充商品作为默认值
 * @param obj
 */
function obtainDiscountRates(obj){
	var plateId = $(obj).val();
	if (!plateId) {
		return;
	}
    jQuery.ajax({
        async: true,
        type:"post",
        url:appServer + "/plate/ajax/plateInfo.json",
        dataType:"json",
        data:{"plateId":plateId},
        success: function(result){
        	console.log(result);
        	if(result.code == 0){
                var data = $.parseJSON(result.data);
                $("#discountRates").val(data.discountRates);
        	}
        },
        error: function(){
        }
    });
}

